package com.googlecode.utterlyidle.multipart;

import com.googlecode.totallylazy.Callable1;
import com.googlecode.utterlyidle.Entity;
import com.googlecode.utterlyidle.HeaderParameters;

import java.io.UnsupportedEncodingException;

import static com.googlecode.utterlyidle.Entity.DEFAULT_CHARACTER_SET;
import static com.googlecode.utterlyidle.Rfc2616.HTTP_BODY_SEPARATOR;

public class Part {
    private final HeaderParameters headers;
    private final Entity entity;

    public Part(HeaderParameters headers, Entity entity) {
        this.headers = headers;
        this.entity = entity;
    }

    public static Part part(HeaderParameters headers, Entity entity) {
        return new Part(headers, entity);
    }

    public HeaderParameters headers() {
        return headers;
    }

    public Entity entity() {
        return entity;
    }

    @Override
    public String toString() {
        return new StringBuilder(headers().toString()).
                append(HTTP_BODY_SEPARATOR).
                append(entity()).
                toString();
    }

    public byte[] toBytes() throws UnsupportedEncodingException {
        byte[] headers = new StringBuilder(headers().toString()).
                append(HTTP_BODY_SEPARATOR).
                toString().
                getBytes(DEFAULT_CHARACTER_SET);
        return ByteArrays.combine(headers, entity.asBytes());
    }

    public static Callable1<Part, byte[]> asBytes() {
        return new Callable1<Part, byte[]>() {
            @Override
            public byte[] call(Part part) throws Exception {
                return part.toBytes();
            }
        };
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return other instanceof Part && other.toString().equals(toString());
    }
}
